package com.itlong.cloud.push.message;

import com.itlong.cloud.PlatformConstants;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.ssl.SslContext;
import org.jboss.netty.handler.ssl.util.SelfSignedCertificate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/**
 * <desc>
 * websocket长连接服务类.
 * </desc>
 *
 * @createDate 2018/7/5
 */

@Service
public class WebSocketServer {

    @Value("${" + PlatformConstants.PROPERTY_VISITOR_PUSH_MESSAGE_URL + "}")
    private  String PROPERTY_VISITOR_PUSH_MESSAGE_URL;

    @Value("${" + PlatformConstants.PROPERTY_VISITOR_PUSH_MESSAGE_PORT + "}")
    private  String PROPERTY_VISITOR_PUSH_MESSAGE_PORT;

    private static Logger LOG = LoggerFactory.getLogger(WebSocketServer.class);
    static final boolean SSL = System.getProperty("ssl") != null;

    public void run() throws Exception {
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } else {
            sslCtx = null;
        }

        ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

        bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory(sslCtx));

        bootstrap.bind(new InetSocketAddress(PROPERTY_VISITOR_PUSH_MESSAGE_URL, Integer.parseInt(PROPERTY_VISITOR_PUSH_MESSAGE_PORT)));

        //LOG.info("【websocket长连接】Web socket server started at port " + Integer.parseInt(PROPERTY_VISITOR_PUSH_MESSAGE_PORT) + '.');
        //LOG.info("【websocket长连接】Open your browser and navigate to http://"+PROPERTY_VISITOR_PUSH_MESSAGE_URL+":"+  Integer.parseInt(PROPERTY_VISITOR_PUSH_MESSAGE_PORT) + '/');
        System.err.println("Web socket server started at port " + Integer.parseInt(PROPERTY_VISITOR_PUSH_MESSAGE_PORT) + '.');
        System.err.println("Open your browser and navigate to http://"+PROPERTY_VISITOR_PUSH_MESSAGE_URL+":"+ Integer.parseInt(PROPERTY_VISITOR_PUSH_MESSAGE_PORT) + '/');
    }

}